package com.hrt.datasender.datacollect.serial.protocol;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.btcode.reflect.AutoClassLoader;
import com.btcode.reflect.IClassFinder;
import com.btcode.reflect.IClassLoader;

/**
 * 驱动加载器
 * 
 * @author gislin
 *
 */
public final class SerialDataProtocolLoader {

    private String basePacket = "com.hrt.datasender.datacollect.serial.protocol";

    private static volatile SerialDataProtocolLoader instance;

    /**
     * 程序中存在的驱动
     */
    private List<ISerialDataProtocol> existProtocol = null;

    private SerialDataProtocolLoader() {

    }

    public static SerialDataProtocolLoader getInstance() {
        if (instance == null) {
            synchronized (SerialDataProtocolLoader.class) {
                if (instance == null) {
                    instance = new SerialDataProtocolLoader();
                }
            }
        }
        return instance;
    }

    /**
     * 获取系统中存在的串口协议
     * 
     * @param packetName
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public synchronized List<ISerialDataProtocol> getExistProtocol()
            throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {

        if (existProtocol != null && existProtocol.size() > 0) {
            return existProtocol;
        }

        IClassFinder classFinder = new SerialDataProtocolFinder();
        IClassLoader calssLoader = new AutoClassLoader(classFinder);

        List<ISerialDataProtocol> protocolList = new ArrayList<>();
        List<Class<?>> serialDataProtocolClasses = calssLoader.loadClass(getClass(), basePacket);

        for (Class<?> myClass : serialDataProtocolClasses) {
            Object instance = myClass.newInstance();
            protocolList.add((ISerialDataProtocol) instance);
        }

        existProtocol = protocolList;

        return existProtocol;
    }

}
